#!/bin/bash

set -u # Treat unset variables as an error.

FAILED_CONVERSIONS="/config/failed_conversions"
SUCCESSFUL_CONVERSIONS="/config/successful_conversions"
IGNORED_CONVERSIONS="/config/ignored_conversion"

HANDBRAKE_CLI="/usr/bin/HandBrakeCLI --preset-import-file /config/ghb/presets.json"

CONTAINER_INSTANCE_ID="$(cat /config/machine-id)"

# https://gist.github.com/aaomidi/0a3b5c9bd563c9e012518b495410dc0e
VIDEO_FILE_EXTENSIONS_INTERNAL_LIST="\
    webm mkv flv vob ogv ogg rrc gifv mng mov avi qt wmv yuv rm asf amv mp4 \
    m4p m4v mpg mp2 mpeg mpe mpv m4v svi 3gp 3g2 mxf roq nsv flv f4v f4p f4a \
    f4b mod"

if [ "${HANDBRAKE_DEBUG:-0}" -eq 1 ]; then
    HANDBRAKE_CLI="$HANDBRAKE_CLI --verbose=3"
fi

# QSV decoding can crash with x264 8-bit files.
# https://github.com/jlesage/docker-handbrake/issues/347
if HandBrakeCLI --help 2>/dev/null | grep -q disable-qsv-decoding
then
    HANDBRAKE_CLI="$HANDBRAKE_CLI --disable-qsv-decoding"
fi

WATCHDIR_HASH="$(mktemp -d)"

OUTPUT_DIR_TMP=""

CURRENT_LOCK_VIDEO=
CURRENT_LOCK_WF=

clean_exit() {
    rm -rf "$WATCHDIR_HASH"
    killall HandBrakeCLI 2>/dev/null
    killall yad 2>/dev/null
    while killall -0 HandBrakeCLI 2>/dev/null; do
        sleep 1
    done
    if [ -n "${OUTPUT_DIR_TMP:-}" ]; then
        rm -rf "$OUTPUT_DIR_TMP"
    fi
    if [ -n "$CURRENT_LOCK_VIDEO" ] && [ -n "$CURRENT_LOCK_WF" ]; then
        unlock_video "$CURRENT_LOCK_VIDEO" "$CURRENT_LOCK_WF"
    fi
}
trap "clean_exit" EXIT

log() {
    echo "$*"
}

is_dir_writable() {
    local tmpfile
    local rc

    tmpfile="$(mktemp "$1"/.test_XXXXXX 2>/dev/null)"
    rc=$?
    rm -f "$tmpfile"
    return "$rc"
}

log_hb_encode_progress() {
    while read -r OUTPUT; do
        echo "Encoding $video: $OUTPUT"
    done | awk 'NR % 12 == 0'
}

log_hb_encode_progress_yad() {
    # Ignore the output if GUI progress or HandBrake GUI are disabled.
    if is-bool-val-true "$AC_NO_GUI_PROGRESS" || is-bool-val-false "${HANDBRAKE_GUI:-1}"
    then
        while read -r OUTPUT; do
            # Do nothing with the output.
            :
        done
        return
    fi

    (
        while read -r OUTPUT; do
            # This control the progress bar.
            echo "$OUTPUT" | cut -d',' -f2- | cut -d' ' -f2 2>/dev/null
            # This put the text inside the progress bar.
            echo "# $OUTPUT" 2>/dev/null
        done
    ) | /opt/base/bin/yad \
            --fixed \
            --width=384 \
            --posx=$(expr $DISPLAY_WIDTH / 2 - 384 / 2) \
            --posy=5 \
            --title "Automatic Video Converter" \
            --window-icon /opt/novnc/images/icons/master_icon.png \
            --borders 10 \
            --text "Encoding $(echo "$video" | sed 's/&/&amp;/g')..." \
            --no-buttons \
            --progress \
            2>/dev/null
}

WATCHDIR_HASH_calculate() {
    local watchdir="$1"
    find "$watchdir" -follow -type f -not -path '*/\.*' -printf '%T@:%s:%p:%m\n' | md5sum | cut -d' ' -f1
}

WATCHDIR_HASH_isset() {
    local watchdir="$1"
    [ -f "$WATCHDIR_HASH/$watchdir/hash" ]
}

WATCHDIR_HASH_update() {
    local watchdir="$1"
    mkdir -p "$WATCHDIR_HASH/$watchdir"
    WATCHDIR_HASH_calculate "$watchdir" > "$WATCHDIR_HASH/$watchdir/hash"
}

WATCHDIR_HASH_changed() {
    local watchdir="$1"
    [ ! -f "$WATCHDIR_HASH/$watchdir/hash" ] || \
    [ "$(cat "$WATCHDIR_HASH/$watchdir/hash")" != "$(WATCHDIR_HASH_calculate "$watchdir")" ]
}

get_video_hash() {
    local video="$1"
    if [ -f "$video" ]; then
        stat -c '%n %s %Y' "$video" | md5sum | cut -d' ' -f1
    else
        find "$video" -type f -exec stat -c '%n %s %Y' {} \; | md5sum | cut -d' ' -f1
    fi
}

get_video_titles() {
    local video="$1"

    $HANDBRAKE_CLI -i "$video" \
                   -t0 \
                   --min-duration "$AC_SOURCE_MIN_DURATION" 2>&1 |
    grep "^+ title " | sed 's/^+ title \([0-9]\+\):$/\1/'
    return ${PIPESTATUS[0]}
}

get_video_lock_dname() {
    local video="$1"
    local wf="$2"
    local lock_dname
    lock_dname="$(echo "$video" | sed "s|^$wf||" | tr '/' '.')".lock
    echo "$lock_dname"
}

lock_video() {
    local video="$1"
    local wf="$2"

    if ! is_dir_writable "$wf"; then
        return 0
    fi

    local lock_dname
    local err
    local rc

    lock_dname="$(get_video_lock_dname "$video" $"$wf")"
    err="$(mkdir "$wf"/"$lock_dname" 2>&1)"
    rc=$?

    if [ "$rc" -eq 0 ]; then
        CURRENT_LOCK_VIDEO="$video"
        CURRENT_LOCK_WF="$wf"
        mkdir "$wf"/"$lock_dname"/"$CONTAINER_INSTANCE_ID"
        return 0
    else
        if echo "$err" | grep -iq "File exists"; then
            return 1
        else
            return 2
        fi
    fi
}

unlock_video() {
    local video="$1"
    local wf="$2"
    local lock_dname
    lock_dname="$(get_video_lock_dname "$video" $"$wf")"
    rm -rf "$wf"/"$lock_dname"

    CURRENT_LOCK_VIDEO=
    CURRENT_LOCK_WF=
}

process_video() {
    local video="$1"
    local wf="$2"

    # Skip video if it doesn't exists (may have been removed while processing
    # the watch directory).
    if [ ! -f "$video" ] && [ ! -d "$video" ]; then
        log "Skipping '$video': no longer exists."
        return
    fi

    # Get hash of the video from its properties.
    local hash
    hash="$(get_video_hash "$video")"

    # Skip video if it has been already successfully processed.
    if [ -f "$SUCCESSFUL_CONVERSIONS" ] && grep -q -w "$hash" "$SUCCESSFUL_CONVERSIONS"; then
        log "Skipping video '$video' ($hash): already processed successfully."
        return
    fi

    # Skip video if we already failed to process it.
    if [ -f "$FAILED_CONVERSIONS" ] && grep -q -w "$hash" "$FAILED_CONVERSIONS"; then
        log "Skipping '$video' ($hash): already processed with failure."
        return
    fi

    # Skip video if it has been ignored.
    if [ -f "$IGNORED_CONVERSIONS" ] && grep -q -w "$hash" "$IGNORED_CONVERSIONS"; then
        log "Skipping video '$video' ($hash): has been processed by another instance."
        return
    fi

    # Skip video if it is not readable.
    if [ ! -r "$video" ]; then
        log "Skipping '$video': not readable, check permissions."
        return
    fi

    # Skip video if it is being processed by another instance.
    lock_video "$video" "$wf"
    local lock_rc=$?
    if [ "$lock_rc" -eq 1 ]; then
        echo "$video $hash" >> "$IGNORED_CONVERSIONS"
        log "Skipping '$video': currently beging processed by another instance."
        return
    elif [ "$lock_rc" -eq 2 ]; then
        log "ERROR: Unable to acquire lock for video '${video}' (${hash})."
        return
    fi

    # Skip video if it is not stable.
    log "Waiting $AC_SOURCE_STABLE_TIME seconds before processing '$video'..."
    sleep "$AC_SOURCE_STABLE_TIME"
    if [ "$hash" != "$(get_video_hash "$video")" ]; then
        log "Skipping '$video': currently being copied."
        unlock_video "$video" "$wf"
        return
    fi

    # Set the output directory.
    case "$AC_OUTPUT_SUBDIR" in
        UNSET)
            OUTPUT_DIR="$AC_OUTPUT_DIR"
            ;;
        SAME_AS_SRC)
            dirname="$(dirname "$video" | sed "s|^$wf||")"
            OUTPUT_DIR="$AC_OUTPUT_DIR/$dirname"
            ;;
        *)
            OUTPUT_DIR="$AC_OUTPUT_DIR/$AC_OUTPUT_SUBDIR"
            ;;
    esac
    OUTPUT_DIR="$(echo "$OUTPUT_DIR" | sed 's|/\+|/|g' | sed 's|/\+$||')"

    # Get the file extension.
    local video_file_ext="${video##*.}"

    # Determine if the extension is in the list of video file extensions.
    local file_ext_in_video_list
    if echo "$AC_VIDEO_FILE_EXTENSIONS" | grep -iwq "$video_file_ext"; then
        file_ext_in_video_list=true
    else
        file_ext_in_video_list=false
    fi

    # Determine if the extension is in the list of non-video file extensions.
    local file_ext_in_non_video_list
    if echo "$AC_NON_VIDEO_FILE_EXTENSIONS" | grep -iwq "$video_file_ext"; then
        file_ext_in_non_video_list=true
    else
        file_ext_in_non_video_list=false
    fi

    # Get video titles.
    local video_titles="UNSET"
    local video_titles_retval
    if $file_ext_in_video_list && $file_ext_in_non_video_list; then
        log "ERROR: File '${video}' (${hash}) has an extension defined as both a video and non-video file."
        unlock_video "$video" "$wf"
        return
    elif [ -n "$AC_VIDEO_FILE_EXTENSIONS" ] && ! $file_ext_in_video_list; then
        log "File '${video}' (${hash}) has an extension not part of the inclusion list."
        video_titles=UNSET
        video_titles_retval=1
    elif $file_ext_in_non_video_list; then
        log "File '${video}' (${hash}) has an extension part of the exclusion list."
        video_titles=UNSET
        video_titles_retval=1
    else
        # Let Handbrake detects if the file is a video or not.
        video_titles="$(get_video_titles "$video")"
        video_titles_retval=$?
        if [ "$video_titles_retval" -ne 0 ]; then
            # File is not a video.
            video_titles=UNSET

            if $file_ext_in_video_list; then
                # The file extension is part of the video file extension list.
                # Make sure to fail the conversion and not consider the file
                # as a non-video.
                video_titles_retval=0
            elif echo "$VIDEO_FILE_EXTENSIONS_INTERNAL_LIST" | grep -iwq "$video_file_ext"; then
                # The file extension is part of our internal list.  Make sure to
                # fail the conversion and not consider the file as a non-video.
                # This is a protection against Handbrake not correctly detecting
                # a video because of a bug, crash, missing support, etc.
                video_titles_retval=0
            fi
        fi
        video_titles="${video_titles:-UNSET}"
    fi

    hb_rc=0

    # Get number of video titles.
    local num_video_titles
    if [ "$video_titles" != "UNSET" ]; then
        num_video_titles="$(echo "$video_titles" | wc -l)"
    else
        num_video_titles="0"
    fi

    if [ "$video_titles_retval" -gt 0 ] && [ "$AC_NON_VIDEO_FILE_ACTION" = "copy" ]; then
        log "File '$video' ($hash) is not a video, copying (unchanged) to output..."
        mkdir -p "$OUTPUT_DIR"
        cp -p "${video}" "${OUTPUT_DIR}/$(basename "${video}")" # "-p" maintains permissions, times etc...
    elif [ "$video_titles_retval" -gt 0 ]; then
        log "File '$video' ($hash) is not a video, ignoring..."
    elif [ "$num_video_titles" -eq 0 ]; then
        log "ERROR: Could not identify titles in '${video}' (${hash})."
        hb_rc=1
    else
        # If main title detection is enabled, force the number of titles to 1.
        if [ "$AC_SOURCE_MAIN_TITLE_DETECTION" != "0" ]; then
            num_video_titles="1"
        fi

        log "Starting conversion of '${video}' (${hash}) using preset '${AC_PRESET}'..."
        log "${num_video_titles} title(s) to process."
    fi

    local title
    local cur_video_title=0

    for title in $video_titles; do
        [ "$title" != "UNSET" ] || continue

        cur_video_title="$(expr $cur_video_title + 1)"
        [ "$num_video_titles" -eq 1 ] || log "Processing title $title ($cur_video_title/$num_video_titles)..."

        # Get the output file basename: start with the one of the input file.
        basename="$(basename "$video" | sed 's/\.[^.]*$//')"
        # If multiple titles, add the '.title-XX' suffix.
        [ "$num_video_titles" -eq 1 ] || basename="$basename.title-$title"

        # Now set the final output filename by adding the extension.
        OUTPUT_FILE="$OUTPUT_DIR/$basename.$AC_FORMAT"

        # Call pre conversion hook.
        if [ -f /config/hooks/pre_conversion.sh ]; then
            log "Executing pre-conversion hook..."
            /bin/sh /config/hooks/pre_conversion.sh "$OUTPUT_FILE" "$video" "$AC_PRESET"
            log "Pre-conversion hook exited with $?"
        fi

        # Skip video if it doesn't exists (may have been removed by the
        # pre-conversion hook).
        if [ ! -f "$video" ] && [ ! -d "$video" ]; then
            log "Skipping '$video': no longer exists."
            continue
        fi

        # Check whether destination already exists
        if [ -f "$OUTPUT_FILE" ] && is-bool-val-false "$AC_OVERWRITE_OUTPUT"; then
            hb_rc=1
            log "ERROR: Destination file '$OUTPUT_FILE' already exists."
            break
        elif [ -f "$OUTPUT_FILE" ] && [ "$AC_OVERWRITE_OUTPUT" == "1" ]; then
            log "WARNING: Overwriting '$OUTPUT_FILE'"
        fi

        # Call the custom HandBrake args hook.
        HANDBRAKE_HOOK_CUSTOM_ARGS=
        if [ -f /config/hooks/hb_custom_args.sh ]; then
            log "Executing custom HandBrake args hook..."
            args="$(/bin/sh /config/hooks/hb_custom_args.sh "$video" "$AC_PRESET")"
            hook_rc=$?
            log "Custom HandBrake args hook exited with $hook_rc"

            if [ $hook_rc -eq 0 ]; then
                HANDBRAKE_HOOK_CUSTOM_ARGS="$(echo "$args" | head -n1)"
            fi
        fi

        # Set the temporary output directory: this is where the video will be
        # actually written before being moved its final location once conversion is
        # terminated.
        OUTPUT_DIR_TMP="$(mktemp -d "$AC_OUTPUT_DIR/.XXXXXX")"
        if [ ! -d "$OUTPUT_DIR_TMP" ]; then
            hb_rc=1
            log "ERROR: Failed to create temporary directory under '$AC_OUTPUT_DIR'."
            break
        fi

        # Set the temporary output filename.
        OUTPUT_FILE_TMP="$OUTPUT_DIR_TMP/$basename.$AC_FORMAT"

        local title_arg=""
        if [ "$AC_SOURCE_MAIN_TITLE_DETECTION" == "0" ]; then
            title_arg="--title $title"
        else
            title_arg="--main-feature"
        fi

        # Invoke HandBrake.
        echo "------- CONVERSION OUTPUT $(date) -------" >> \
            /config/log/hb/conversion.log
        $HANDBRAKE_CLI -i "$video" \
                       -o "$OUTPUT_FILE_TMP" \
                       $title_arg \
                       --preset "$AC_PRESET" \
                       $HANDBRAKE_HOOK_CUSTOM_ARGS \
                       $AC_HANDBRAKE_CUSTOM_ARGS 2>> \
            /config/log/hb/conversion.log | \
            /usr/bin/unbuffer -p grep "^Encoding" | \
            stdbuf -oL cut -d' ' -f2- | \
            tee >(log_hb_encode_progress) >(log_hb_encode_progress_yad) > /dev/null
        hb_rc=$?

        # Close YAD window.
        killall -SIGUSR1 yad 2> /dev/null

        # Make sure the output file has been generated.
        if [ $hb_rc -eq 0 ] && [ ! -f "$OUTPUT_FILE_TMP" ]; then
            hb_rc=1
        fi

        # Move the file to its final location if conversion terminated
        # successfully.
        if [ $hb_rc -eq 0 ]; then
            mkdir -p "$OUTPUT_DIR"
            mv -f "$OUTPUT_FILE_TMP" "$OUTPUT_FILE"
        fi
        rm -rf "$OUTPUT_DIR_TMP"
        OUTPUT_DIR_TMP=""

        # Call post conversion hook.
        if [ -f /config/hooks/post_conversion.sh ]; then
            log "Executing post-conversion hook..."
            /bin/sh /config/hooks/post_conversion.sh $hb_rc "$OUTPUT_FILE" "$video" "$AC_PRESET"
            log "Post-conversion hook exited with $?"
        fi

        [ $hb_rc -eq 0 ] || break
    done

    NUM_PROCESSED_FILES="$(expr $NUM_PROCESSED_FILES + 1)"

    if [ $hb_rc -eq 0 ]; then
        log "Conversion ended successfully."
        echo "$video $hash" >> "$SUCCESSFUL_CONVERSIONS"
        if is-bool-val-false "$AC_KEEP_SOURCE"; then
            if is-bool-val-false "$AC_USE_TRASH"; then
                log "Removing '$video'..."
                rm -rf "$video"
                if [ $? -eq 0 ]; then
                    log "Removed '$video'."
                else
                    log "ERROR: Could not remove '$video'."
                fi
            else
                VIDEO_TRASH_PATH="$AC_TRASH_DIR/${video#"$wf"}"
                mkdir -p "$(dirname "$VIDEO_TRASH_PATH")"
                log "Moving '$video' to trash directory '$AC_TRASH_DIR'..."
                mv "$video" "$VIDEO_TRASH_PATH"
                if [ $? -eq 0 ]; then
                    log "Moved '$video' to trash directory."
                else
                    log "ERROR: Could not move '$video' to trash directory."
                fi
            fi
            # Remove directory if empty (hidden files/folders are ignored).
            local videodir
            videodir="$(dirname "$video")"
            while [ "$videodir" != "$wf" ] && [ -z "$(ls "$videodir")" ]; do
                rm -rf "$videodir"
                if [ $? -eq 0 ]; then
                    log "Removed directory '$videodir'."
                else
                    log "ERROR: Could not remove directory '$videodir'."
                fi
                videodir="$(dirname "$videodir")"
            done
        fi
    else
        log "Conversion failed."
        log "For more details about the failure, see /config/log/hb/conversion.log."
        if ! echo "$AC_PRESET" | grep -q "/"; then
            log "NOTE: The configured preset doesn't seem to include its category.  A preset must"
            log "      must now be identified using the following format: '<CATEGORY>/<PRESET NAME>'."
            log "      This may be the cause of the current failure."
        fi
        echo "$video $hash" >> "$FAILED_CONVERSIONS"
    fi

    unlock_video "$video" "$wf"
}

process_watch_folder() {
    local wf="$1"

    NUM_PROCESSED_FILES=0

    # Return now if the watch folder doesn't exist.
    [ -d "$wf" ] || return

    # Remove any left-over locks for our own instance.
    find "$wf" -mindepth 1 -maxdepth 1 -type d -name "*.lock" | while read -r d; do
        if [ -e "$d"/"$CONTAINER_INSTANCE_ID" ]; then
            rm -rf "$d"
        fi
    done

    # Return now if the watch folder didn't change.
    WATCHDIR_HASH_changed "$wf" || return

    # Make sure the output directory is properly setup.
    if [ ! -d "$AC_OUTPUT_DIR" ]; then
        log "ERROR: Cannot process watch folder '$wf', because the associated output directory '$AC_OUTPUT_DIR' doesn't exist."
        return
    elif ! is_dir_writable "$AC_OUTPUT_DIR"; then
        log "ERROR: Cannot process watch folder '$wf', because the associated output directory '$AC_OUTPUT_DIR' is not writable."
        return
    fi

    if WATCHDIR_HASH_isset "$wf"; then
        log "Change detected in watch folder '$wf'."
    fi

    # Make sure to update the watch directory hash before processing it.
    # This is to make sure we catch, on the next round, changes occuring
    # during the processing.
    WATCHDIR_HASH_update "$wf"

    log "Processing watch folder '$wf'..."
    local filelist1
    local filelist2
    filelist1="$(mktemp)"
    filelist2="$(mktemp)"

    # First, get the list of files in the watch folder, filtering all files
    # files under VIDEO_TS or BDMV and keeping only their parent directory.
    find "$wf" -follow -type f -not -path '*/\.*' -printf "%T@ %p\n" | \
        sort -n | \
        cut -d' ' -f2- | \
        sed 's|/\([^/]*\)/VIDEO_TS/.*$|/\1|g' | \
        sed 's|/\([^/]*\)/BDMV/.*$|/\1|g' | \
        uniq > "$filelist1"
    cp "$filelist1" "$filelist2"

    # Then, remove all files under directories part of the list.  The
    # directories from the list are video discs and their individual files
    # should not be processed.
    while read -u 3 f
    do
        if [ -d "$f" ]; then
            sed -i "s|$f/.*|$f|g" "$filelist2"
        fi
    done 3<"$filelist1"
    cat "$filelist2" | uniq > "$filelist1"

    # Warn user if video disc folder structure is found at the root of the watch
    # folder.
    for DIR in "$wf/VIDEO_TS" "$wf/BDMV"
    do
        if [ -d "$DIR" ]; then
            log "Skipping '$DIR': video disc folder structure should not be placed at the root of the watch folder."
        fi
    done

    # Process videos files.
    while read -u 3 f
    do
        if [ "$f" = "$wf" ]; then
            continue
        fi
        process_video "$f" "$wf"
    done 3<"$filelist1"
    rm "$filelist1"
    rm "$filelist2"
    log "Watch folder '$wf' processing terminated."

    # Call watch folder done hook.
    if [ -f /config/hooks/post_watch_folder_processing.sh ] && [ "$NUM_PROCESSED_FILES" -gt 0 ]; then
        log "Executing post watch folder processing hook..."
        /bin/sh /config/hooks/post_watch_folder_processing.sh "$wf"
        log "Post watch folder processing hook exited with $?"
    fi
}

[ -f "$FAILED_CONVERSIONS" ] || touch "$FAILED_CONVERSIONS"
[ -f "$SUCCESSFUL_CONVERSIONS" ] || touch "$SUCCESSFUL_CONVERSIONS"
[ -f "$IGNORED_CONVERSIONS" ] || touch "$IGNORED_CONVERSIONS"

while true; do
    for i in $(seq 1 ${AUTOMATED_CONVERSION_MAX_WATCH_FOLDERS:-5}); do
        # Set default settings.
        AC_PRESET="${AUTOMATED_CONVERSION_PRESET:-Very Fast 1080p30}"
        AC_FORMAT="${AUTOMATED_CONVERSION_FORMAT:-mp4}"
        AC_SOURCE_STABLE_TIME="${AUTOMATED_CONVERSION_SOURCE_STABLE_TIME:-5}"
        AC_SOURCE_MIN_DURATION="${AUTOMATED_CONVERSION_SOURCE_MIN_DURATION:-10}"
        AC_SOURCE_MAIN_TITLE_DETECTION="${AUTOMATED_CONVERSION_SOURCE_MAIN_TITLE_DETECTION:-0}"
        AC_WATCH_DIR="${AUTOMATED_CONVERSION_WATCH_DIR:-AUTO}"
        AC_OUTPUT_DIR="${AUTOMATED_CONVERSION_OUTPUT_DIR:-/output}"
        AC_OUTPUT_SUBDIR="${AUTOMATED_CONVERSION_OUTPUT_SUBDIR:-UNSET}"
        AC_KEEP_SOURCE="${AUTOMATED_CONVERSION_KEEP_SOURCE:-1}"
        AC_VIDEO_FILE_EXTENSIONS="${AUTOMATED_CONVERSION_VIDEO_FILE_EXTENSIONS:-}"
        AC_NON_VIDEO_FILE_ACTION="${AUTOMATED_CONVERSION_NON_VIDEO_FILE_ACTION:-ignore}"
        AC_NON_VIDEO_FILE_EXTENSIONS="${AUTOMATED_CONVERSION_NON_VIDEO_FILE_EXTENSIONS:-jpg jpeg bmp png gif txt nfo}"
        AC_NO_GUI_PROGRESS="${AUTOMATED_CONVERSION_NO_GUI_PROGRESS:-0}"
        AC_HANDBRAKE_CUSTOM_ARGS="${AUTOMATED_CONVERSION_HANDBRAKE_CUSTOM_ARGS:-}"
        AC_OVERWRITE_OUTPUT="${AUTOMATED_CONVERSION_OVERWRITE_OUTPUT:-0}"
        AC_USE_TRASH="${AUTOMATED_CONVERSION_USE_TRASH:-0}"
        AC_TRASH_DIR="${AUTOMATED_CONVERSION_TRASH_DIR:-/trash}"

        # Apply per-watch folder settings.
        for VAR in PRESET FORMAT SOURCE_STABLE_TIME SOURCE_MIN_DURATION SOURCE_MAIN_TITLE_DETECTION WATCH_DIR OUTPUT_DIR OUTPUT_SUBDIR KEEP_SOURCE VIDEO_FILE_EXTENSIONS NON_VIDEO_FILE_ACTION NON_VIDEO_FILE_EXTENSIONS NO_GUI_PROGRESS HANDBRAKE_CUSTOM_ARGS OVERWRITE_OUTPUT USE_TRASH TRASH_DIR
        do
            eval "AC_$VAR=\"\${AUTOMATED_CONVERSION_${VAR}_${i}:-\$AC_$VAR}\""
        done

        # Set the watch folder path.
        dir="$AC_WATCH_DIR"
        if [ "$AC_WATCH_DIR" = "AUTO" ]; then
            if [ "$i" -eq 1 ]; then
                dir="/watch"
            else
                dir="/watch$i"
            fi
        fi

        # Process watch folder.
        process_watch_folder "$dir"
    done

    sleep "${AUTOMATED_CONVERSION_CHECK_INTERVAL:-5}"
done

# vim:ft=sh:ts=4:sw=4:et:sts=4
